package org.codefinger.dao.impl.sql.ast;

import org.codefinger.dao.impl.SQLVisitor;
import org.codefinger.dao.impl.sql.Expression;

public class NamedLeftLikeExpression implements Expression {

	private String	param;

	public NamedLeftLikeExpression(String param) {
		super();
		this.param = param;
	}

	@Override
	public boolean matchVisit(SQLVisitor visitor) {
		Object obj = visitor.getParam(param);
		if (obj == null) {
			return false;
		}
		visitor.addParam(getLeftLike(obj.toString()));
		visitor.appendSQL('?');
		return true;
	}

	@Override
	public void visit(SQLVisitor visitor) {
		visitor.addParam(getLeftLike(String.valueOf(visitor.getParam(param))));
		visitor.appendSQL('?');
	}

	public static String getLeftLike(String like) {
		int length = like.length();
		char[] chars = new char[length + 1];
		chars[length] = '%';
		like.getChars(0, length, chars, 0);
		return new String(chars);
	}

}
